package com.strato.mvc.i18n.v1_0_0.resolvers;

import java.util.Locale;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.strato.mvc.i18n.v1_0_0.LocaleResolver;

public class CookieResolver implements LocaleResolver {

	private static CookieResolver instance=new CookieResolver();
	
	public static CookieResolver getInstance() {
		return instance;
	}

	public static final String COOKIE_NAME="locale";
	
	@Override
	public Locale load(HttpServletRequest request, HttpServletResponse response) {
		Cookie[] cookies = request.getCookies();
		if(cookies!=null){
			for(Cookie cookie:cookies){
				if(COOKIE_NAME.equals(cookie.getName())){
					String localeName = cookie.getValue();
					return Locale.forLanguageTag(localeName);
				}
			}
		}
		return null;
	}

	@Override
	public void save(Locale locale, HttpServletRequest request, HttpServletResponse response) {
		String sl=null;
		if(locale!=null){
			sl=locale.toLanguageTag();
		}
		Cookie cookie=new Cookie(COOKIE_NAME,sl);
		response.addCookie(cookie);
	}

}
